const channel = new MessageChannel();
const output = /** @type {HTMLElement} */ (document.querySelector(".output"));
const iframe = /** @type {HTMLIFrameElement} */ (
  document.querySelector("iframe")
);

// Wait for the iframe to load
iframe?.addEventListener("load", onLoad);

/**
 * @returns {void}
 */
function onLoad() {
  // Listen for messages on port1
  channel.port1.onmessage = onMessage;
  // Transfer port2 to the iframe
  iframe?.contentWindow?.postMessage(
    "A message from the index.html page!",
    "*",
    [channel.port2],
  );
}
/**
 * @param {MessageEvent} e
 */
// Handle messages received on port1
function onMessage(e) {
  output.innerText = e.data;
}
